package com.gitee.feizns.quickstart.qi.niu;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import lombok.Getter;
import lombok.SneakyThrows;

import java.io.InputStream;

/**
 * 七牛云工具类
 * @author feizns
 * @since 2023/2/8
 */
@Getter
public class QiNiuUtils {

    /**
     * {@link QiNiuConfig}
     */
    private final QiNiuConfig config;

    /**
     * {@link Auth}
     */
    private final Auth auth;

    /**
     * 配置
     */
    private final Configuration cfg = new Configuration(Region.autoRegion());

    /**
     * 上传管理器
     */
    private final UploadManager uploadManager = new UploadManager(cfg);

    /**
     * 配置上传服务
     * @param config {@link QiNiuConfig}
     */
    public QiNiuUtils(QiNiuConfig config) {
        this.config = config;
        auth = Auth.create(config.getAccessKey(), config.getSecretKey());
    }

    /**
     * 获取上传凭证
     * @return {@link String}
     */
    public String uploadToken() {
        return auth.uploadToken(config.getBucket());
    }

    /**
     * 放
     * @param key 钥匙
     * @param is 是否是
     * @return {@link Response }
     */
    @SneakyThrows
    public Response put(String key, InputStream is) {
        return uploadManager.put(IOUtils.toByteArray(is), key, uploadToken());
    }

    /**
     * 获取私有下载链接
     * @param url 网址
     * @return {@link String }
     */
    public String privateDownloadUrl(String url) {
        return auth.privateDownloadUrl(url);
    }

}
